package com.udata.server.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class AbstractServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 5809993163071923365L;

	protected void sendResponseMsg(HttpServletResponse response, String content)
			throws IOException {

		try {
			response.setHeader("Cache-Control", "no-store");
			response.setHeader("Pragma", "no-cache");
			response.setContentType("text/plain");
			response.setCharacterEncoding("UTF-8");
			ServletOutputStream responseOutputStream = response
					.getOutputStream();

			responseOutputStream.write(content.getBytes("UTF-8"));
			responseOutputStream.flush();
			responseOutputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getBody(HttpServletRequest request) throws IOException {

		String body = null;
		StringBuilder stringBuilder = new StringBuilder();
		BufferedReader bufferedReader = null;

		try {
			InputStream inputStream = request.getInputStream();
			if (inputStream != null) {
				bufferedReader = new BufferedReader(new InputStreamReader(
						inputStream));
				char[] charBuffer = new char[128];
				int bytesRead = -1;
				while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
					stringBuilder.append(charBuffer, 0, bytesRead);
				}
			} else {
				stringBuilder.append("");
			}
		} catch (IOException ex) {
			throw ex;
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException ex) {
					throw ex;
				}
			}
		}

		body = stringBuilder.toString();
		return body;
	}

	protected HashMap<String, String> getParameterMap(String payloadRequest) {
		HashMap<String, String> result = new HashMap<String, String>();
		String[] parameterArray = payloadRequest.split("&");
		for (String parameter : parameterArray) {
			String[] keyValue = parameter.split("=");
			result.put(keyValue[0], keyValue[1]);
		}
		return result;

	}

}
